package com.ttn.student.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ttn.common.core.entity.Result;
import com.ttn.common.core.entity.business.Order;
import com.ttn.common.core.entity.studentrecord.StudentRecord;
import com.ttn.common.core.entity.studentrecord.query.StudentRecordQuery;
import com.ttn.student.service.StudentRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 学员记录(StudentRecord)表控制层
 *
 * @author makejava
 * @since 2023-01-30 15:57:40
 */
@RestController
@Slf4j
@RequestMapping("student-record")
public class StudentRecordController {
    /**
     * 服务对象
     */
    @Resource
    private StudentRecordService studentRecordService;

    /**
     * 新增学员
     *
     * @param request
     * @param studentRecord
     * @return
     */
    @PostMapping("/save/student-record")
    public Result saveStudentRecord(HttpServletRequest request, @RequestBody StudentRecord studentRecord) {
        log.info("StudentRecordController saveAssignProductQuality ,参数:{}", studentRecord);
        LambdaQueryWrapper<StudentRecord> studentRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
        studentRecordLambdaQueryWrapper.eq(StudentRecord::getCellPhoneNumber, studentRecord.getCellPhoneNumber());
        if (studentRecordService.count(studentRecordLambdaQueryWrapper) > 0) {
            return Result.fail("重复手机号，确认后重试");
        }
        studentRecordService.saveStudentRecord(studentRecord);
        return Result.success();
    }

    /**
     * 保存用户测评结果
     *
     * @param request
     * @param studentRecord
     * @return
     */
    @PostMapping("/save/student-record-evaluation")
    public Result saveStudentRecordEvaluation(HttpServletRequest request, @RequestBody StudentRecord studentRecord) {
        log.info("StudentRecordController saveStudentRecordEvaluation ,参数:{}", studentRecord);

        studentRecordService.updateById(studentRecord);
        return Result.success();
    }

    /**
     * 修改学员
     *
     * @param request
     * @param studentRecord
     * @return
     */

    @PutMapping("/modify/student-record")
    public Result modifyStudentRecord(HttpServletRequest request, @RequestBody StudentRecord studentRecord) {
        log.info("StudentRecordController modifyStudentRecord ,参数:{}", studentRecord);
        LambdaQueryWrapper<StudentRecord> studentRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
        studentRecordLambdaQueryWrapper.eq(StudentRecord::getCellPhoneNumber, studentRecord.getCellPhoneNumber());
        studentRecordLambdaQueryWrapper.ne(StudentRecord::getId, studentRecord.getId());
        if (studentRecordService.count(studentRecordLambdaQueryWrapper) > 0) {
            return Result.fail("重复手机号，确认后重试");
        }
        studentRecordService.updateById(studentRecord);
        return Result.success();
    }

    @PutMapping("/service/modify/student-record-deadLine")
    public Result modifyStudentRecordDeadLine(@RequestBody Order order) {
        log.info("StudentRecordController modifyStudentRecordDeadLine ,参数:{}", order);
        StudentRecord studentRecord = studentRecordService.getById(order.getStudentId());
        if (Objects.nonNull(studentRecord.getDeadLine())) {
            if (DateUtil.compare(order.getPaymentTime(), studentRecord.getDeadLine()) >= 0) {
                studentRecord.setDeadLine(DateUtil.offsetDay(order.getPaymentTime(), order.getServicePeriod() + 1));
            } else {
                studentRecord.setDeadLine(DateUtil.offsetDay(studentRecord.getDeadLine(), order.getServicePeriod() + 1));
            }

        } else {
            studentRecord.setDeadLine(DateUtil.offsetDay(order.getPaymentTime(), order.getServicePeriod() + 1));
        }
        studentRecord.setStudentType(2);
        studentRecordService.updateById(studentRecord);
        return Result.success();
    }

    /**
     * 分页查询学生列表情况
     *
     * @param request
     * @param studentRecordQuery
     * @return
     */
    @PostMapping("/query/student-record-page")
    public Result queryStudentRecordPage(HttpServletRequest request, @RequestBody StudentRecordQuery studentRecordQuery) {
        log.info("StudentRecordController queryStudentRecordPage ,参数:{}", studentRecordQuery);
        return studentRecordService.queryStudentRecordPage(studentRecordQuery);
    }

    /**
     * 通过学生id，获取用户信息（内部接口）
     *
     * @param id
     * @return
     */
    @PostMapping("/service/query/student-record-by-id/{id}")
    public Result serviceQueryStudentRecordById(@PathVariable Integer id) {
        log.info("StudentRecordController serviceQueryStudentRecordById ,参数:{}", id);
        return Result.success(studentRecordService.getById(id));
    }

    @PostMapping("/service/query/student-login")
    public Result serviceQueryStudentLogin(@RequestBody StudentRecord studentRecord) {
        log.info("StudentRecordController serviceQueryStudentLogin ,参数:{}", studentRecord);
        LambdaQueryWrapper<StudentRecord> studentRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
        studentRecordLambdaQueryWrapper.eq(StudentRecord::getOpenId, studentRecord.getOpenId());
        StudentRecord queryStudentRecord = studentRecordService.getOne(studentRecordLambdaQueryWrapper);
        if (Objects.nonNull(queryStudentRecord)) {
            LambdaUpdateWrapper<StudentRecord> studentRecordLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            studentRecordLambdaUpdateWrapper.eq(StudentRecord::getId, queryStudentRecord.getId());
            studentRecordLambdaUpdateWrapper.set(StrUtil.isNotBlank(studentRecord.getToken()), StudentRecord::getToken, studentRecord.getToken());
            studentRecordLambdaUpdateWrapper.set(StrUtil.isNotBlank(studentRecord.getUnionId()), StudentRecord::getAvatarUrl, studentRecord.getAvatarUrl());
            if (StrUtil.isNotBlank(queryStudentRecord.getNickName())) {
                studentRecordLambdaUpdateWrapper.set(StrUtil.isNotBlank(studentRecord.getNickName()), StudentRecord::getNickName, studentRecord.getNickName());
            }
            studentRecordLambdaUpdateWrapper.set(StudentRecord::getLastLogin, DateTime.now());
            studentRecordLambdaUpdateWrapper.set(StrUtil.isNotBlank(studentRecord.getCellPhoneNumber()), StudentRecord::getCellPhoneNumber, studentRecord.getCellPhoneNumber());
            studentRecordService.update(studentRecordLambdaUpdateWrapper);
            studentRecord = studentRecordService.getById(queryStudentRecord.getId());
            return Result.success(studentRecord);
        } else {
            studentRecord.setLastLogin(DateTime.now());
            studentRecord.setStudentType(1);
            Result<StudentRecord> studentRecordResult = studentRecordService.saveStudentRecord(studentRecord);
            return studentRecordResult;
        }
    }

    /**
     * 通过id，获取详情
     *
     * @param id
     * @return
     */
    @PostMapping("/query/student-record-by-id/{id}")
    public Result queryStudentRecordById(@PathVariable Integer id) {
        log.info("StudentRecordController queryStudentRecordById ,参数:{}", id);
        return studentRecordService.queryStudentRecordById(id);
    }

    /**
     * 通过openId查询
     *
     * @param openid
     * @return
     */
    @PostMapping("/service/query/student-record-by-openid/{openid}")
    public Result queryStudentRecordByOpenId(@PathVariable("openid") String openid) {
        log.info("StudentRecordController queryStudentRecordByOpenId ,参数openid:{}", openid);
        LambdaQueryWrapper<StudentRecord> studentRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
        studentRecordLambdaQueryWrapper.eq(StudentRecord::getOpenId, openid);
        return Result.success(studentRecordService.getOne(studentRecordLambdaQueryWrapper));
    }

    @PostMapping("/query/admin-student-record-by-id/{id}")
    public Result queryAdminStudentRecordById(@PathVariable Integer id) {
        log.info("StudentRecordController queryAdminStudentRecordById ,参数:{}", id);
        return studentRecordService.queryAdminStudentRecordById(id);
    }

}

